package net.web.controller;

import net.web.common.framework.simplemvc.RequestMapping;
import net.web.common.utils.JSONUtil;
import net.web.common.utils.PageInfo;
import net.web.common.utils.Result;
import net.web.entity.User;
import net.web.service.UserService;
import net.web.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.List;

@RequestMapping("/api/user")
public class UserController {

    private UserService userService = new UserServiceImpl();

    @RequestMapping("/register.do")
    public void register(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");

        String username = req.getParameter("username");
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String confirmPassword = req.getParameter("confirmPassword");

        if (username == null || username.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户名不能为空"));
            return;
        }
        if (email == null || email.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("邮箱不能为空"));
            return;
        }
        if (password == null || password.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("密码不能为空"));
            return;
        }
        if (!password.equals(confirmPassword)) {
            JSONUtil.printByJSON(resp, Result.fail("两次密码不一致"));
            return;
        }

        if (userService.existsByUsername(username)) {
            JSONUtil.printByJSON(resp, Result.fail("用户名已存在"));
            return;
        }
        if (userService.existsByEmail(email)) {
            JSONUtil.printByJSON(resp, Result.fail("邮箱已存在"));
            return;
        }

        User user = new User();
        user.setUsername(username);
        user.setEmail(email);
        user.setPassword(password);
        user.setBio("");
        user.setLikedArticles("");
        user.setCollectedArticles("");

        if (userService.register(user)) {
            JSONUtil.printByJSON(resp, Result.success("注册成功"));
        } else {
            JSONUtil.printByJSON(resp, Result.fail("注册失败"));
        }
    }

    @RequestMapping("/login.do")
    public void login(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");

        String loginName = req.getParameter("loginName");
        String password = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");

        if (loginName == null || loginName.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户名或邮箱不能为空"));
            return;
        }
        if (password == null || password.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("密码不能为空"));
            return;
        }

        User user = userService.login(loginName, password);
        if (user != null) {
            HttpSession session = req.getSession();
            session.setAttribute("user", user);

            if ("true".equals(rememberMe)) {
                session.setMaxInactiveInterval(30 * 24 * 60 * 60);
            }

            JSONUtil.printByJSON(resp, Result.success(user, "登录成功"));
        } else {
            JSONUtil.printByJSON(resp, Result.fail("用户名或密码错误"));
        }
    }

    @RequestMapping("/logout.do")
    public void logout(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        JSONUtil.printByJSON(resp, Result.success("退出登录成功"));
    }

    @RequestMapping("/checkLogin.do")
    public void checkLogin(HttpServletRequest req, HttpServletResponse resp) {
        HttpSession session = req.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("user");
            if (user != null) {
                JSONUtil.printByJSON(resp, Result.success(user, "用户已登录"));
                return;
            }
        }
        JSONUtil.printByJSON(resp, Result.fail("用户未登录"));
    }

    @RequestMapping("/profile.do")
    public void profile(HttpServletRequest req, HttpServletResponse resp) {
        String userIdStr = req.getParameter("userId");
        if (userIdStr == null || userIdStr.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
            return;
        }

        try {
            int userId = Integer.parseInt(userIdStr);
            User user = userService.findById(userId);
            if (user != null) {
                user.setPassword(null);
                JSONUtil.printByJSON(resp, Result.success(user));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("用户不存在"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID格式错误"));
        }
    }

    @RequestMapping("/updateProfile.do")
    public void updateProfile(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");

        String userIdStr = req.getParameter("userId");
        String email = req.getParameter("email");
        String bio = req.getParameter("bio");
        String userPicture = req.getParameter("userPicture");

        if (userIdStr == null || userIdStr.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
            return;
        }

        try {
            int userId = Integer.parseInt(userIdStr);
            User existingUser = userService.findById(userId);
            if (existingUser == null) {
                JSONUtil.printByJSON(resp, Result.fail("用户不存在"));
                return;
            }

            if (email != null && !email.equals(existingUser.getEmail())) {
                if (userService.existsByEmailExcludeId(email, userId)) {
                    JSONUtil.printByJSON(resp, Result.fail("邮箱已存在"));
                    return;
                }
                existingUser.setEmail(email);
            }

            if (bio != null) {
                existingUser.setBio(bio);
            }
            if (userPicture != null) {
                existingUser.setUserPicture(userPicture);
            }

            if (userService.updateProfile(existingUser)) {
                existingUser.setPassword(null);
                JSONUtil.printByJSON(resp, Result.success(existingUser, "更新成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("更新失败"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID格式错误"));
        }
    }

    @RequestMapping("/changePassword.do")
    public void changePassword(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");

        String userIdStr = req.getParameter("userId");
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String confirmPassword = req.getParameter("confirmPassword");

        if (userIdStr == null || userIdStr.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
            return;
        }
        if (oldPassword == null || oldPassword.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("原密码不能为空"));
            return;
        }
        if (newPassword == null || newPassword.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("新密码不能为空"));
            return;
        }
        if (!newPassword.equals(confirmPassword)) {
            JSONUtil.printByJSON(resp, Result.fail("两次密码不一致"));
            return;
        }

        try {
            int userId = Integer.parseInt(userIdStr);
            if (userService.updatePassword(userId, oldPassword, newPassword)) {
                JSONUtil.printByJSON(resp, Result.success("密码修改成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("原密码错误"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID格式错误"));
        }
    }

    @RequestMapping("/pageList.do")
    public void pageList(HttpServletRequest req, HttpServletResponse resp) {
        String pageNoStr = req.getParameter("pageNo");
        String pageSizeStr = req.getParameter("pageSize");
        int pageNo = pageNoStr == null || pageNoStr.isEmpty() ? 1 : Integer.parseInt(pageNoStr);
        int pageSize = pageSizeStr == null || pageSizeStr.isEmpty() ? 10 : Integer.parseInt(pageSizeStr);

        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setEmail(req.getParameter("email"));
        user.setRole(parseInt(req.getParameter("role"), -1));

        PageInfo<User> pageInfo = userService.pageList(pageNo, pageSize, user);

        for (User u : pageInfo.getRecords()) {
            u.setPassword(null);
        }

        JSONUtil.printByJSON(resp, Result.success(pageInfo));
    }

    @RequestMapping("/update.do")
    public void update(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");

        String idStr = req.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
            return;
        }

        try {
            int id = Integer.parseInt(idStr);
            User existingUser = userService.findById(id);
            if (existingUser == null) {
                JSONUtil.printByJSON(resp, Result.fail("用户不存在"));
                return;
            }

            String email = req.getParameter("email");
            String bio = req.getParameter("bio");
            String roleStr = req.getParameter("role");
            String userPicture = req.getParameter("userPicture");

            if (email != null && !email.equals(existingUser.getEmail())) {
                if (userService.existsByEmailExcludeId(email, id)) {
                    JSONUtil.printByJSON(resp, Result.fail("邮箱已存在"));
                    return;
                }
                existingUser.setEmail(email);
            }

            if (bio != null) {
                existingUser.setBio(bio);
            }
            if (roleStr != null && !roleStr.trim().isEmpty()) {
                existingUser.setRole(Integer.parseInt(roleStr));
            }
            if (userPicture != null) {
                existingUser.setUserPicture(userPicture);
            }

            if (userService.update(existingUser)) {
                JSONUtil.printByJSON(resp, Result.success("更新成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("更新失败"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(resp, Result.fail("参数格式错误"));
        }
    }

    @RequestMapping("/delete.do")
    public void delete(HttpServletRequest req, HttpServletResponse resp) {
        String idStr = req.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID不能为空"));
            return;
        }

        try {
            int id = Integer.parseInt(idStr);
            if (userService.delete(id)) {
                JSONUtil.printByJSON(resp, Result.success("删除成功"));
            } else {
                JSONUtil.printByJSON(resp, Result.fail("删除失败"));
            }
        } catch (NumberFormatException e) {
            JSONUtil.printByJSON(resp, Result.fail("用户ID格式错误"));
        }
    }

    @RequestMapping("/generateAvatar.do")
    public void generateAvatar(HttpServletRequest req, HttpServletResponse resp) {
        String username = req.getParameter("username");
        String sizeStr = req.getParameter("size");

        if (username == null || username.trim().isEmpty()) {
            JSONUtil.printByJSON(resp, Result.fail("用户名不能为空"));
            return;
        }

        int size = 100;
        if (sizeStr != null && !sizeStr.trim().isEmpty()) {
            try {
                size = Integer.parseInt(sizeStr);
            } catch (NumberFormatException e) {
                size = 100;
            }
        }

        String avatarUrl = userService.generateAvatar(username, size);
        JSONUtil.printByJSON(resp, Result.success(avatarUrl, "生成成功"));
    }

    private int parseInt(String val, int defaultVal) {
        if (val == null || val.trim().isEmpty()) return defaultVal;
        try {
            return Integer.parseInt(val.trim());
        } catch (NumberFormatException e) {
            return defaultVal;
        }
    }
}
